//
//  LoginViewController.m
//  觅影
//
//  Created by lanou on 16/4/12.
//  Copyright © 2016年  陶虹. All rights reserved.
//

#import "LoginViewController.h"
#import "AppDelegate.h"
#import "RootViewController.h"

@interface LoginViewController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *keyTextField;

@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;

@property (weak, nonatomic) IBOutlet UIButton *loginButton;


@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.loginButton addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    self.keyTextField.delegate = self;
    self.passwordTextField.delegate = self;
    
}

- (void)loginAction:(UIButton *)button
{
    
    NSString *username = self.keyTextField.text;
    NSString *password = self.passwordTextField.text;
    NSDictionary *parDic = @{@"pwd":password, @"username":username};
        [RequestManager requestWithUrl:@"http://static.v6v7.com/snowman_api/user/username_login" requestType:RequestTypePOST parDic:parDic finshed:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSString *msgString = dic[@"msg"];
            NSString *msg = [msgString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
            if ([msg isEqualToString:@"账号错误"]) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"提示" message:@"账号错误" preferredStyle:UIAlertControllerStyleActionSheet];
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                    [sheet addAction:cancelAction];
                    [self presentViewController:sheet animated:YES completion:nil];
                });

            }
            else if ([msg isEqualToString:@"密码错误"])
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"提示" message:@"密码错误" preferredStyle:UIAlertControllerStyleActionSheet];
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                    [sheet addAction:cancelAction];
                    [self presentViewController:sheet animated:YES completion:nil];
                });
            }
            else
            {
                NSDictionary *resultDic = dic[@"result"];
                NSString *myid = resultDic[@"uid"];
                dispatch_async(dispatch_get_main_queue(), ^{
//                        UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"提示" message:@"登陆成功" preferredStyle:UIAlertControllerStyleActionSheet];
//                        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//                        [sheet addAction:cancelAction];
//                        [self presentViewController:sheet animated:YES completion:nil];
                    
                    // 登录成功 把登陆的状态保存到服务器 把姓名和密码保存到服务器
                    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"isLogin"];
                    [[NSUserDefaults standardUserDefaults]setObject:self.keyTextField.text forKey:@"username"];
                    [[NSUserDefaults standardUserDefaults]setObject:self.passwordTextField.text forKey:@"pwd"];
                    [[NSUserDefaults standardUserDefaults] setObject:myid forKey:@"myid"];
                    // 切换根视图
                    RootViewController *rootVC = [[RootViewController alloc]init];
                    [UIApplication sharedApplication].delegate.window.rootViewController = rootVC;
                });
            }

        } error:^(NSError *error) {
            NSLog(@"请求错误");
        }];
}

#pragma mark --- 点击空白回收键盘 ---
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.keyTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}

#pragma mark --- 点击return回收键盘 ---
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.keyTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    return YES;
}

#pragma mark --- 跳转到注册界面 ---
- (IBAction)registerAction:(id)sender
{
   [UIView transitionFromView:self.view toView:self.registerVC.view duration:1 options:UIViewAnimationOptionTransitionFlipFromLeft completion:nil];
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
